import axios, {
  AxiosInstance,
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig,
  AxiosRequestConfig,
} from 'axios'
import { Resp } from '@/types/resp.ts'
import { ApiError } from '@/error/ApiError.ts'

const baseURL = window.location.origin + '/api'

const service: AxiosInstance = axios.create({
  timeout: 5000,
  baseURL: baseURL,
})

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response.data
    } else {
      return Promise.reject()
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)
/**
 * 后端返回状态非200时抛出自定义异常ApiError
 * @param config
 */
const request = async <T = unknown>(config: AxiosRequestConfig) => {
  const res: Resp<T> = await service(config)
  if (res.code !== 200) {
    throw new ApiError(res.code, res.message)
  }
  return res.data
}
export default request
